<script setup>
import {User, Lock, Phone} from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/userStore.js'
import { useRouter } from 'vue-router'
import {ElMessage} from "element-plus";
import {getCodeAPI, registerAPI} from "@/api/user.js";

const isRegister = ref(false)
const form = ref()

defineOptions({
  name: "LoginPage",
})

// 整个的用于提交的form数据对象
const formModel = ref({
  username: '',
  password: '',
  code: '',
  phone: '',
  rememberMe: false,
})
// 注册表单的校验规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
}

// 登录表单的校验规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const time = ref(0) // 时间
const timer = ref(null) // 定时器
// 获取验证码
const getCode = async () => {
  try {
    time.value = 60
    timer.value = setInterval(() => {
      time.value--

      if (time.value === 0) {
        clearInterval(timer.value)
      }
    }, 1000)

    const res = await getCodeAPI(formModel.value.phone)
    if (res.code === 200) {
      ElMessage.success('验证码为：' + res.data)
    }
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

const register = async () => {
  try {
    // 注册成功之前，先进行校验，校验成功 → 请求，校验失败 → 自动提示
    await form.value.validate()
    const res = await registerAPI(formModel.value)
    if (res.code === 200) {
      ElMessage.success('注册成功')
      isRegister.value = false
    }
  } catch (error) {
    ElMessage.error('注册失败')
  }
}

const userStore = useUserStore()
const router = useRouter()
const login = async () => {
  await form.value.validate()
  try {
    await userStore.login(formModel.value)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (e) {
    ElMessage.error('登录失败')
  }
}

// 切换的时候，重置表单内容
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: '',
    code: '',
    phone: ''
  }
})
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册相关表单 -->
      <el-form
        :model="formModel"
        :rules="registerRules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            :prefix-icon="Phone"
            type="text"
            placeholder="请输入手机号"
            v-model="formModel.phone"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div class="code">
            <el-input
              :prefix-icon="Lock"
              type="text"
              placeholder="请输入验证码"
              class="code-input"
              v-model="formModel.code"
            ></el-input>
            <el-button class="code-btn" type="primary" :disabled="time != 0" @click="getCode">{{ time ? `${time}秒后重新获取` : '获取验证码' }}</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录相关表单 -->
      <el-form
        :model="formModel"
        :rules="loginRules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="formModel.rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url('@/assets/images/hstc0.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .code {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .code-input {
        width: 65%;
      }
      .code-btn {
        width: 30%;
      }
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
